package com.rerun.common.shiro.redisCache;

import java.io.Serializable;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RedisSessionDao extends AbstractSessionDAO {

	@Autowired
	private RedisManager redisManager;

	Logger log = LoggerFactory.getLogger(getClass());

	@Override
	public void update(Session session) throws UnknownSessionException {
		HttpServletRequest request = Servlets.getRequest();
		if (request != null) {
			String uri = request.getServletPath();
			// 如果是静态文件，则不更新SESSION
			if (Servlets.isStaticFile(uri)) {
				return;
			}
			// 如果是视图文件，则不更新SESSION
			if (StringUtils.startsWith(uri, "WEB-INF/views/")
					&& StringUtils.endsWith(uri, "html")) {
				return;
			}
			log.info("更新session,id=[{}]", session.getId().toString());
			try {
				redisManager.hadd(session.getId().toString(), session);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	@Override
	public void delete(Session session) {
		log.info("删除session,id=[{}]", session.getId().toString());
		try {
			redisManager.hdelete(session.getId().toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public Collection<Session> getActiveSessions() {
		log.info("获取存活的session");
		return redisManager.hmget();
	}

	@Override
	protected Serializable doCreate(Session session) {
		Serializable sessionId = generateSessionId(session);
		assignSessionId(session, sessionId);
		// ((SerSession)session).setId(sessionId);
		log.info("创建session,id=[{}]", session.getId().toString());
		try {
			redisManager.hadd(sessionId.toString(), session);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return sessionId;
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		Session s = null;
		HttpServletRequest request = Servlets.getRequest();
		if (request != null){
			String uri = request.getServletPath();
			// 如果是静态文件，则不获取SESSION
			if (Servlets.isStaticFile(uri)){
				return null;
			}
			s = (Session)request.getAttribute("shiroSesssion");
		}
		if (s != null){
			return s;
		}
		log.info("获取session,id=[{}]", sessionId.toString());
		return redisManager.hget(sessionId.toString());
	}
}
